import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { LoginRequest, TokenPair, User } from '@/api/types'
import { useAuthApi } from '@/api/modules/auth'
import notify from '@/utils/notify'
import { logger } from '@/utils/logger'

/**
 * 用户 Store
 * 管理认证状态和用户信息
 */
export const useUserStore = defineStore('user', () => {
  // State
  const token = ref<string | null>(localStorage.getItem('token'))
  const userInfo = ref<User | null>(null)

  // Actions

  /**
   * 登录
   */
  async function login(data: LoginRequest): Promise<boolean> {
    try {
      logger.debug('Login attempt started', { username: data.username })
      const api = useAuthApi()
      const response: TokenPair = await api.login(data)
      logger.debug('Login API response received')
      token.value = response.access_token
      localStorage.setItem('token', response.access_token)
      // 可选：存储刷新令牌与过期时间以支持自动刷新
      localStorage.setItem('refresh_token', response.refresh_token)
      localStorage.setItem('token_expires_at', response.expires_at)
      logger.debug('Fetching user info after login')
      await fetchUserInfo()
      logger.info('Login successful', { userId: userInfo.value?.id, role: userInfo.value?.role })
      return true
    } catch (error: unknown) {
      logger.error('Login failed', { error: error instanceof Error ? error.message : 'Unknown error' })
      // 类型安全的错误处理
      const axiosError = error as { response?: { status?: number; data?: { detail?: string } }; message?: string; code?: string }
      const status = axiosError?.response?.status
      const detail = axiosError?.response?.data?.detail || axiosError?.message
      if (!axiosError?.response) {
        const code = axiosError?.code
        if (code === 'ECONNABORTED') {
          notify.error('登录请求超时，请检查网络或稍后重试')
        } else {
          notify.error('无法连接后端，请确认 http://localhost:8000 已启动')
        }
      } else if (status === 401) {
        notify.error('用户名或密码错误')
      } else if (status === 403) {
        notify.error('当前账号没有权限登录该系统')
      } else if (status === 500) {
        notify.error('服务器繁忙，请稍后重试')
      } else {
        notify.error(detail || '登录失败，请稍后重试')
      }
      return false
    }
  }

  /**
   * 登出
   */
  function logout() {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('token')
  }

  /**
   * 获取用户信息
   */
  async function fetchUserInfo() {
    try {
      if (!token.value) {
        logger.debug('No token available, skipping user info fetch')
        return null
      }
      logger.debug('Fetching user info from /me endpoint')
      const api = useAuthApi()
      const user = await api.me()
      logger.debug('User info fetched successfully', { userId: user.id, email: user.email })
      userInfo.value = user
      return user
    } catch (error) {
      logger.error('Failed to fetch user info', { error: error instanceof Error ? error.message : 'Unknown error' })
      return null
    }
  }

  return {
    token,
    userInfo,
    login,
    logout,
    fetchUserInfo,
  }
})
